package pub.guoxin.oops.common.base.log;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pub.guoxin.oops.annotation.InjectUser;
import pub.guoxin.oops.common.base.log.annotation.LogIgnore;
import pub.guoxin.oops.model.User;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

/**
 * 日志记录切面
 *
 * @author shenyonggang
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(* pub.guoxin.oops..*Controller.*(..))")
    public void webLog() {
    }

    /**
     * 记录请求参数
     *
     * @param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        if (annotationExists(signature))
            return;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        int injectUserIndex = getInjectUserIndex(joinPoint);
        if (injectUserIndex != -1) {
            args = getNoInjectUserArgs(args, injectUserIndex);
        }

        log.info("=======================================================================");
        log.info("URL\t: " + request.getRequestURL().toString());
        log.info("ARGS\t: " + Arrays.toString(args));
    }

    /**
     * 记录响应结果
     *
     * @param joinPoint
     * @param ret
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        if (annotationExists(signature)) {
            return;
        }
        log.debug("RESPONSE\t: " + ret);
        log.info("TIME\t: " + (System.currentTimeMillis() - startTime.get()) + "ms");
        log.info("=======================================================================");
    }

    /**
     * 方法上是否存在LogIgnore注解
     *
     * @param signature
     * @return true | false
     */
    private boolean annotationExists(MethodSignature signature) {
        Method method = signature.getMethod();
        Class declaringType = signature.getDeclaringType();
        Class<LogIgnore> logIgnoreClass = LogIgnore.class;
        Annotation classAnno = declaringType.getAnnotation(logIgnoreClass);
        if (!Objects.isNull(classAnno)) // 类上面的注解
            return true;
        Annotation methodAnno = method.getAnnotation(logIgnoreClass);
        return !Objects.isNull(methodAnno);// 方法上面的注解
    }

    /**
     * 获得不包含InjectUser注解的参数列表
     *
     * @param oldArgs
     * @param injectUserIndex
     * @return
     */
    private Object[] getNoInjectUserArgs(Object[] oldArgs, int injectUserIndex) {
        ArrayList<Object> args = Lists.newArrayList();
        for (int i = 0; i < oldArgs.length; i++) {
            if (injectUserIndex == i)
                continue;
            args.add(oldArgs[i]);
        }
        return args.toArray();
    }

    /**
     * 获得包含InjectUser注解的参数下标
     *
     * @param joinPoint
     * @return
     */
    private int getInjectUserIndex(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();
        Method method = signature.getMethod();
        for (int i = 0; i < args.length; i++) { // 参数列表
            MethodParameter methodParameter = new SynthesizingMethodParameter(method, i);
            Class<?> parameterType = methodParameter.getParameterType();
            if (!parameterType.equals(User.class)) {
                continue;
            }
            Annotation[] annotations = methodParameter.getParameterAnnotations();
            // 循环参数上所有的注解
            for (Annotation annotation : annotations) {
                if (!(annotation instanceof InjectUser)) {
                    continue;
                }
                return i;
            }
        }
        return -1;
    }

}
